// todo: 统一网络请求客户端
import 'package:dio/dio.dart';

import 'config/api_constants.dart';
import 'exceptions/api_exceptions.dart';
import 'interceptors/auth_interceptor.dart';
import 'interceptors/cache_interceptor.dart';
import 'interceptors/retry_interceptor.dart';
import 'models/api_response.dart';

enum HttpMethod { get, post, put, delete, patch }

class ApiClient {
  final Dio _dio;
  final NetworkConfig config;

  ApiClient._(this._dio, this.config);

  factory ApiClient.create(NetworkConfig config) {
    final dio = Dio(BaseOptions(
      baseUrl: config.baseUrl,
      connectTimeout: config.connectTimeout,
      receiveTimeout: config.receiveTimeout,
    ));

    final client = ApiClient._(dio, config);
    client._addInterceptors();
    return client;
  }

  void _addInterceptors() {
    if (config.enableLogging) {
      _dio.interceptors.add(LogInterceptor(
        requestHeader: true,
        responseHeader: true,
      ));
    }

    _dio.interceptors.addAll([
      AuthInterceptor(
        getAccessToken: () async => 'your_token',
        refreshToken: () async => 'new_token',
      ),
      RetryInterceptor(maxRetries: config.maxRetries),
      if (config.enableCache) CacheInterceptor(),
    ]);
  }

  Future<ApiResponse<T>> request<T>(
    String path, {
    HttpMethod method = HttpMethod.get,
    dynamic data,
    Map<String, dynamic>? queryParams,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
    bool useCache = false,
  }) async {
    try {
      final response = await _dio.request(
        path,
        data: data,
        queryParameters: queryParams,
        options: Options(
          method: method.name.toUpperCase(),
          extra: {'use_cache': useCache},
        ),
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress,
      );

      return _handleResponse<T>(response);
    } on DioException catch (e) {
      return ApiResponse.error(UnknowResponseException(e));
    }
  }

  ApiResponse<T> _handleResponse<T>(Response response) {
    final statusCode = response.statusCode;
    if (statusCode == ApiConstants.successCode) {
      return ApiResponse.success(
        data: response.data,
        headers: response.headers.map,
      );
    } else {
      return ApiResponse.error(
        BusinessException(
          code: statusCode ?? ApiConstants.networkErrorCode,
          message: '业务异常',
          data: response.data,
        ),
      );
    }
  }
}




/* 
// 普通使用配置
NetworkConfig config = NetworkConfig(
  baseUrl: 'https://api.example.com',  // 替换为你自己的接口地址
  connectTimeout: 5000,                // 设置连接超时，单位为毫秒
  receiveTimeout: 5000,                // 设置响应超时，单位为毫秒
  enableLogging: true,                 // 是否启用日志记录
  enableCache: true,                   // 是否启用缓存
  maxRetries: 3,                       // 最大重试次数
);

ApiClient apiClient = ApiClient.create(config);

// riverpod配置
final apiClientProvider = Provider<ApiClient>((ref) {
  return ApiClient.create(const NetworkConfig(
    baseUrl: ApiConstants.appBaseUrl,
    enableLogging: !kReleaseMode,
  ));
});


// 业务层调用
class UserRepository {
  final ApiClient _client;

  UserRepository(this._client);

  Future<ApiResponse<User>> getUserInfo(String userId) async {
    return _client.request(
      '/user/$userId',
      method: HttpMethod.get,
    ).then((response) => response.when(
      success: (data) => ApiResponse.success(
        data: User.fromJson(data),
      ),
      error: (e) => ApiResponse.error(e),
    ));
  }
}

// 错误处理
void handleError(ApiResponse response) {
  response.when(
    success: (data) => print(data),
    error: (error) {
      if (error is UnauthorizedException) {
        // 跳转登录
      } else if (error is BusinessException) {
        showToast(error.message);
      } else {
        showToast('系统异常');
      }
    },
  );
}

// get请求
final response = await apiClient.request(
  '/path/to/endpoint',              // 接口路径
  method: HttpMethod.get,           // 请求方式：GET
  queryParams: {'id': 123},         // 查询参数
);

// post请求
final response = await apiClient.request(
  '/path/to/endpoint',              // 接口路径
  method: HttpMethod.post,          // 请求方式：POST
  data: {'name': 'John', 'age': 30}, // 请求体数据
);

// 带文件上传的post请求
final formData = FormData.fromMap({
  'file': await MultipartFile.fromFile('/path/to/file', filename: 'file.jpg'),
});

final response = await apiClient.request(
  '/upload',
  method: HttpMethod.post,
  data: formData,
);

// 处理响应
if (response.isSuccess) {
  // 请求成功
  print('数据：${response.data}');
} else {
  // 请求失败
  print('错误：${response.errorMessage}');
}



*/